package admin

import (
	"night-school-api/models"
	"night-school-api/utils"
	"night-school-api/database"
	"night-school-api/middlewares"

	"time"
	"errors"
	"fmt"

	"github.com/labstack/echo/v4"
	"golang.org/x/crypto/bcrypt"
)

// 定义 JSON 请求数据结构
type adminLoginRequest struct {
	Username string `json:"username" validate:"min=6"`
	Password string `json:"password" validate:"min=6"`
}

type adminLoginResponse struct {
	Token    string      `json:"token"`
	UserInfo models.Admin `json:"user_info"`
}


// 后台登录
func AdminLogin(c echo.Context) error {
	var req adminLoginRequest

	// 解析 JSON 请求
	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "参数错误")
	}

	if err := c.Validate(&req); err != nil {
		return err
	}

	db := database.DB

	var admin models.AdminWithPasswd
	db.Model(&models.AdminWithPasswd{}).Where("username = ?", req.Username).First(&admin)

	
	// c.Logger().Info(fmt.Sprintf("admin: %T %v", admin.Passwd, admin.Passwd))

	if admin.ID == 0 {
		return utils.JSONError(c, "用户名或密码错误")
	}

	if !admin.CheckPasswd(req.Password) {
		return utils.JSONError(c, "用户名或密码错误")
	}

	var now models.JSONTime
	now.Time = time.Now()

	admin.LastLoginAt = now
	db.Save(&admin)
	
	// 生成token
	token, err := middlewares.GenerateToken(admin.ID, "admin")
	if err != nil {
		c.Logger().Info("系统错误，生成登录凭证失败:" + err.Error())
		return utils.JSONError(c, "系统错误，生成登录凭证失败")
	}

	a := models.Admin{
		ID: admin.ID,
		Name: admin.Name,
		Username: admin.Username,
		CountyIndex: admin.CountyIndex,
		IsSuper: admin.IsSuper,
	}
	data := adminLoginResponse{
		Token:    token,
		UserInfo: a,
	}

	return utils.JSONSuccess(c, data, "")
}

func checkIsSuperAdmin(c echo.Context) error {
	adminUid := c.Get("uid").(int)
	if adminUid <= 0 {
		return errors.New("未登录")
	}

	db := database.DB
	query := db.Model(&models.Admin{})
	var admin models.Admin

	query.Find(&admin, adminUid)
	if admin.ID <= 0 {
		return errors.New("系统错误，管理员账户不存在")
	}
	if admin.IsSuper != 1 {
		return errors.New("您不是超级管理员，不能对管理员进行操作")
	}

	return nil
}

func GetAdmins(c echo.Context) error {
	chekAdminErr := checkIsSuperAdmin(c)
	if chekAdminErr != nil {
		return utils.JSONError(c, chekAdminErr.Error())
	}

	db := database.DB
	query := db.Model(&models.Admin{})

	var total int64
	var admins []models.Admin
	query.Count(&total)
	page, size := utils.GetPagination(c)
	query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&admins)

	return utils.JSONPagination(c, page, size, total, admins)
}

func UpdateAdmin(c echo.Context) error {
	chekAdminErr := checkIsSuperAdmin(c)
	if chekAdminErr != nil {
		return utils.JSONError(c, chekAdminErr.Error())
	}
	
	db := database.DB

	var req models.AdminWithPasswd
	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "参数错误")
	}

	if err := c.Validate(&req); err != nil {
		return err
	}

	if req.Passwd != "" && len(req.Passwd) < 6 {
		return utils.JSONError(c, "密码不能少于6个字符")
	}

	c.Logger().Info(fmt.Sprintf("req: %#v", req))
	
	c.Logger().Info(fmt.Sprintf("%#v", req))

	query := db.Debug().Model(&models.AdminWithPasswd{})

	var err error
	if req.ID == 0 {
		var count int64
		db.Model(&models.AdminWithPasswd{}).Where("username", req.Username).Count(&count)
		if count > 0 {
			return utils.JSONError(c, "管理员登录用户名已存在，不能重复创建")
		}
		err = query.Create(&req).Error
	} else {
		query = query.Where("id =?", req.ID)
		if req.Passwd != "" {
			// Generate hashed password
			hashedPassword, bcErr := bcrypt.GenerateFromPassword([]byte(req.Passwd), bcrypt.DefaultCost)
			if bcErr != nil {
				return utils.JSONError(c, "系统错误")
			}
			db.Table("admins").Where("id = ?", req.ID).Update("passwd", hashedPassword)
		}
		err = query.Updates(map[string]interface{}{
			"name": req.Name,
			"username": req.Username,
			"county_index": req.CountyIndex,
		}).Error
	}
	

	if err != nil {
		c.Logger().Info("保存管理员失败: " + err.Error())
		return utils.JSONError(c, "保存管理员失败")
	} else {
		return utils.JSONSuccess(c, nil, "保存管理员成功")
	}
}


func DeleteAdmin(c echo.Context) error {
	chekAdminErr := checkIsSuperAdmin(c)
	if chekAdminErr != nil {
		return utils.JSONError(c, chekAdminErr.Error())
	}
	

	var req map[string]interface{}
	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "请求参数错误")
	}

	var id int
	idFloat, ok := req["id"].(float64)
	if !ok {
		return utils.JSONError(c, "请求参数错误")
	} else {
		id = int(idFloat)
	}

	if id <= 0 {
		return utils.JSONError(c, "请求参数不合法")
	}

	
	db := database.DB
	query := db.Model(&models.Admin{})
	var admin models.Admin

	query.Find(&admin, id)
	if admin.IsSuper == 1 {
		return errors.New("不能删除超级管理员")
	}

	err := db.Delete(&models.Admin{}, id)

	if err.Error != nil {
		return utils.JSONError(c, "删除失败")
	} else {
		return utils.JSONSuccess(c, nil, "删除成功")
	}
}